package com.stu.controller;

import com.stu.pojo.CustomerTokenDTO;
import com.stu.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class WebSocketCouponProducer {

    private static final String TOKEN_HEADER = "Authorization";
    private static final String TOKEN_PREFIX = "Bearer ";

    @Autowired
    private AmqpTemplate rabbitTemplate;

    @PostMapping("/coupon/websocket")
    public ResponseEntity<?> sendCouponMessage(@RequestHeader(TOKEN_HEADER) String authHeader) {
        // 1. 验证并解析Token
        String token = extractToken(authHeader);
        Claims claims = JwtUtil.parseToken(token);

        // 2. 构建消息体
        Map<String, Object> message = new HashMap<>();
        message.put("userId", claims.getSubject());
        message.put("userName", claims.get("userName", String.class)); // 假设JWT中包含用户名

        // 3. 发送RabbitMQ消息
        rabbitTemplate.convertAndSend(
                "webSocketCouponExchange",
                "zhtCoupon",
                message
        );

        // 4. 返回标准化响应
        return ResponseEntity.ok().body(Map.of(
                "success", true,
                "message", "优惠券消息推送成功"
        ));
    }

    private String extractToken(String authHeader) {
        if (authHeader == null || !authHeader.startsWith(TOKEN_PREFIX)) {
            throw new IllegalArgumentException("无效的授权头");
        }
        return authHeader.substring(TOKEN_PREFIX.length());
    }
}